#!/bin/sh
# Copyright (c) 2010 Tomas Carnecky

M=`date +%M`
M=$((M%45))
[ $M -eq 0 ] && exit 0
#exit 0

BINPATH="/conf/sbin"
CONFPATH="/conf/.config"

if [ -s $CONFPATH/tweakpack.conf ]; then
    . $CONFPATH/tweakpack.conf
fi

# *************
# Path to transmission-remote
REMOTE="$BINPATH/transmission-remote 127.0.0.1:9091 -n $PASS"

# Maximum number of torrents that may be active at any given time
MAXACTIVE="2"

[ -f /conf/.cron/queue.lock ] && exit 0
touch /conf/.cron/queue.lock

# *************
# Stop all finished torrents
LIST="$($REMOTE -l | grep -v "Status" | grep -v "^Sum\:" | grep 100% | grep -v Stopped | awk '{ print $1; }')"
for ID in $LIST; do
    NAME="$($REMOTE -t $ID -i | grep Name:)"
    NAME="${NAME#*Name: }"
#    echo "$ID | $NAME"
    SEED=`$BINPATH/seed.sh "$NAME" | wc -l`
#    echo "<<< $ID: ${NAME#*Name: }"
    if [ $SEED -eq 0 ]; then
        $REMOTE -t $ID --stop >/dev/null
    fi
done
            
# How many are still running?
ACTIVE="$($REMOTE -l | grep -v "Status" | grep -v Stopped | grep -v 100% | grep -v "^Sum\:" | wc -l)"
if [ $ACTIVE -gt $MAXACTIVE ]; then
#    echo "Running $ACTIVE torrents. Maximum: $MAXACTIVE"
    rm -f /conf/.cron/queue.lock
    exit
fi
                
# Start new torrents
LIST="$($REMOTE -l | grep -v "Status" | grep -v 100% | grep Stopped | head -n $(expr $MAXACTIVE - $ACTIVE) | awk '{ print $1; }')"
for ID in $LIST; do
    NAME="$($REMOTE -t $ID -i | grep Name:)"
#    echo ">>> $ID: ${NAME#*Name: }"
    $REMOTE -t $ID --start >/dev/null
done

rm -f /conf/.cron/queue.lock

